package com.api.gbhg.wangc.api;

import com.alibaba.fastjson.JSON;
import com.api.gbhg.huangwm.dao.BudgetManagementDownDao;
import com.api.gbhg.huangwm.dao.YuSuanTiaoZhengDao;
import com.api.gbhg.luoao.utils.PageEntity;
import com.api.gbhg.wangc.dao.BudgetManagementDao;
import com.customization.assets.util.DateTools;
import com.engine.common.util.ParamUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.GCONST;
import weaver.general.Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangc
 * @description BudgetManagementApi 项目台账
 * @date 2021/1/21 10:59
 */
@Path("/gbhg/budgetmanagement")
public class BudgetManagementApi {

    public static final Logger logger = LoggerFactory.getLogger("gbhg");

    // 操作sql类
    private BudgetManagementDao budgetManagementDao = new BudgetManagementDao();

    private BudgetManagementDownDao downDao = new BudgetManagementDownDao();

    private DateTools dateTools = new DateTools();

    @POST
    @Path("/getProjectAccountList")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String getProjectAccountList(Map<String, Object> param) {
        try {
            String year = (String) param.get("year");
            String proName = (String) param.get("proName");
            String unitName = (String) param.get("unitName");//使用单位
            String startDate = (String) param.get("startDate");
            String endDate_no = (String) param.get("endDate");
            Integer pageNum = (Integer) param.get("pageNum");
            Integer pageSize = (Integer) param.get("pageSize");
            String sbdw = (String) param.get("sbdw");//申报单位
            String dlhsdw = (String) param.get("dlhsdw");//独立核算单位

            if(year.isEmpty()){
                year = dateTools.getCurrentYear();
            }
            logger.info("经费版本参数,proName:" + proName + ",unitName:" + unitName + ",startDate:" + startDate + ",endDate:" + endDate_no + ",pageNum:" + pageNum + ",pageSize:" + pageSize + ",sbdw:" + sbdw);
            // 查询数据
            RecordSetTrans mainTable = budgetManagementDao.getFundingVersion(proName, unitName, startDate, endDate_no, pageNum, pageSize, param.get("userid").toString(), sbdw,year,dlhsdw);
            // 查询总数
            int total = budgetManagementDao.getMainTableCount(proName, unitName, startDate, endDate_no, param.get("userid").toString(), sbdw,year,dlhsdw);
            PageEntity page = new PageEntity();
            Map<String, Object>[] map = new HashMap[mainTable.getArray().size()];
            int i = 0;
            RecordSet rs1 = new RecordSet();
            RecordSet rs2 = new RecordSet();
            while (mainTable.next()) {
                map[i] = new HashMap<>();
                map[i].put("lcid", mainTable.getInt("lcid"));//流程id
                map[i].put("lcbj", mainTable.getString("lcbj"));//流程标记
                map[i].put("lcjlsqjlid", mainTable.getInt("lcjlsqjlid"));//流程记录申请记录id
                map[i].put("lczt", mainTable.getString("lczt"));//流程状态
                map[i].put("lcztz", mainTable.getString("lcztz"));//流程状态值
                map[i].put("sfky", mainTable.getString("sfky"));//是否可用
                map[i].put("sbdw", budgetManagementDao.getSubCompanyNameById(mainTable.getString("sbdw")));//申报单位
                map[i].put("ysnd", mainTable.getString("ysnd"));//预算年度
                String sfwzjxm = mainTable.getString("sfwzjxm");
                map[i].put("sfwzjxm", (sfwzjxm.isEmpty() || sfwzjxm.equals("0")?"否":"是"));//是否为追加项目
                map[i].put("xmmin", mainTable.getString("xmmin")+"(是否追加:"+(sfwzjxm.isEmpty() || sfwzjxm.equals("0")?"否":"是")+")");//项目名称
                map[i].put("sfzdxm", mainTable.getString("sfzdxm"));//是否重点项目

                //负责人
                if ("1".equals(mainTable.getString("fzr"))) {
                    map[i].put("fzr", "系统管理员");
                } else {
                    if (mainTable.getString("fzr").matches("[0-9]+")) {
                        map[i].put("fzr", budgetManagementDao.getUserNameById(mainTable.getString("fzr")));
                    } else {
                        map[i].put("fzr", mainTable.getString("fzr"));
                    }
                }
                //经办人
                if ("1".equals(mainTable.getString("jbr"))) {
                    map[i].put("jbr", "系统管理员");
                } else {
                    map[i].put("jbr", budgetManagementDao.getUserNameById(mainTable.getString("jbr")));
                }
                String czbk = mainTable.getString("czbk");
                String jzje = mainTable.getString("jzje");
                if (StringUtils.isBlank(czbk)) {
                    czbk = "0.00";
                }
                if (StringUtils.isBlank(jzje)) {
                    jzje = "0.00";
                }
                map[i].put("czbk", Double.valueOf(czbk) > 0 ? BigDecimal.valueOf(mainTable.getDouble("czbk")).setScale(2, RoundingMode.DOWN) : "0.00");//财政拨款
                map[i].put("jzje", Double.valueOf(jzje) > 0 ? BigDecimal.valueOf(mainTable.getDouble("jzje")).setScale(2, RoundingMode.DOWN) : "0.00");//结转金额
                map[i].put("bz", mainTable.getString("bz"));//备注
                map[i].put("sbks", budgetManagementDao.getDepartmentNameById(mainTable.getString("sbks")));//申报科室
                map[i].put("lxdh", mainTable.getString("lxdh"));//联系电话
                map[i].put("gkdw", mainTable.getString("gkdw"));//归口单位
                map[i].put("sydw", mainTable.getString("sydw"));//使用单位
                String requestId = mainTable.getString("requestId");
                //logger.info("项目台账已归档请求id--------"+requestId);
                RecordSetTrans sub = budgetManagementDao.getFundsAmount(requestId);
                if (sub.next()) {
                    RecordSetTrans subTable = budgetManagementDao.getFundsAmount(requestId);
                    BigDecimal bai = new BigDecimal("100");
                    BigDecimal ze = new BigDecimal(0);
                    BigDecimal syed = new BigDecimal(0);
                    BigDecimal djed = new BigDecimal(0);
                    BigDecimal yyed = new BigDecimal(0);
                    BigDecimal yszxl = new BigDecimal(0);
                    BigDecimal yszje = new BigDecimal(0);
                    BigDecimal wan = new BigDecimal("10000");
                    String getYbx = "SELECT ISNULL(SUM(d1.tybxje-ISNULL(d1.cxje,0)),0) as ybx FROM dbo.uf_bxjl_kj_dt1 d1 \n" +
                            "LEFT JOIN uf_bxjl_kj d ON d1.lcid=d.lcid\n" +
                            "LEFT JOIN dbo.workflow_requestbase wr ON d1.lcid=wr.requestid\n" +
                            "WHERE ysxm=" + requestId + "  AND d.shrq<='"+dateTools.getCurrentDate()+"' ";//6月30号前的执行率
                    rs1.execute(getYbx);
                    rs1.next();
//                  String getDj = "SELECT ISNULL(SUM(d1.tybxje-d1.cxje),0) as dj FROM dbo.uf_bxjl_kj_dt1 d1 \n" +
//                            "LEFT JOIN uf_bxjl_kj d ON d1.lcid=d.lcid\n" +
//                            "LEFT JOIN dbo.workflow_requestbase wr ON d1.lcid=wr.requestid\n" +
//                            "LEFT JOIN workflow_base wb ON wr.workflowid=wb.id\n" +
//                            "WHERE ysxm="+requestId+" AND wr.currentnodetype in(1,2)";
                    String getDj = "SELECT ISNULL(SUM(t.sqbxje-isnull(cxje,0)),0) AS dj FROM (\n" +
                            "\tSELECT wr.requestid,jl.lclx,jl.sqbxje,jl.cxje FROM dbo.uf_bxsjjl  jl LEFT JOIN workflow_requestbase wr ON jl.lcid=wr.requestid\n" +
                            "\tWHERE ysxm=" + requestId + " AND wr.currentnodetype IN (1,2)\n" +
                            ")t WHERE t.requestid IS NOT NULL  AND t.requestid NOT IN (SELECT d1.lcid FROM dbo.uf_bxjl_kj_dt1 d1 \n" +
                            "LEFT JOIN uf_bxjl_kj d ON d1.lcid=d.lcid\n" +
                            "WHERE   d.shrq<='"+dateTools.getCurrentDate()+"' AND ysxm="+requestId+" ) ";
                    rs2.execute(getDj);
                    rs2.next();
                    //预算总金额
                    yszje = new BigDecimal(mainTable.getDouble("yszje"));
                    yszje = yszje.divide(wan, 4, BigDecimal.ROUND_HALF_UP);
                    map[i].put("yszje", yszje);
                    while (subTable.next()) {
                        ze = ze.add(new BigDecimal(subTable.getString("ze")));
                        //syed = syed.add(new BigDecimal(subTable.getString("syed")));
                        //djed = djed.add(new BigDecimal(subTable.getString("dj")));
                    }
                    //BigDecimal yyed1 = ze.subtract(syed).subtract(djed);
                    BigDecimal yyed1 = new BigDecimal(rs1.getString("ybx"));
                    djed = new BigDecimal(rs2.getString("dj"));
                    yyed = yyed1.divide(wan, 4, BigDecimal.ROUND_HALF_UP);
                    djed = djed.divide(wan, 4, BigDecimal.ROUND_HALF_UP);
                    if(Double.parseDouble(String.valueOf(ze)) != 0.00){
                        yszxl  = yyed1.divide(ze, 3, BigDecimal.ROUND_CEILING).multiply(bai).setScale(2);
                    }
                    //logger.info(ze + "=总额==" + syed + "=剩余额度==" + djed + "=冻结额度==" + yyed1 + "=已用额度==" + yszxl+",执行率:"+yszxl);
                    map[i].put("yyed", yyed.toString());
                    map[i].put("djed", djed.toString());
                    map[i].put("yszxl", yszxl.toString() + "%");
                    i++;
                }
            }
            page.setList(map);
            page.setPageNumber(pageNum);
            page.setpageSize(pageSize);
            page.setTotal(total);// 数据总数
            page.setPages((total + pageSize - 1) / pageSize);
            logger.info("项目台账获取返回total：" + total);
            return JSON.toJSONString(page);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("项目台账获取返回异常" + e.getMessage());
            return e.getMessage();
        }

    }

    /**
     * 小数转换为百分数
     *
     * @param number
     * @return
     */
    public static String conversionPercentage(double number) {
        DecimalFormat df = new DecimalFormat("0.00%");
        BigDecimal d = new BigDecimal(number);
        String percent = df.format(d);
        return percent;
    }

    public static void main(String[] args) {
        BigDecimal divide = BigDecimal.valueOf(0).divide(BigDecimal.valueOf(1780), 4, BigDecimal.ROUND_UP);
        String s = conversionPercentage(divide.doubleValue());
        System.out.println(s);
    }


}
